<script setup lang="ts" name="TallyTransfer">
import { onMounted, reactive, ref, watch } from "vue";
import { useDictInfo } from "@/store/dict";
import SelectStorage from "@/components/SelectInfo/SelectStorage.vue";
import { useBillInfo } from "@/store/bill-info";
import BigNumber from "bignumber.js";
import { showFailToast } from "vant";
import SelectShip from "@/components/SelectInfo/SelectShip.vue";
import SelectBill from "@/components/SelectInfo/SelectBill.vue";
import { useEditOstInfo } from "@/store/edit-ost-info";
import { GetStorageDetail } from "@/api/tally";
import { isNumeric } from "vant/es/utils";
import type { StorageData } from "@/utils/interface";

const emit = defineEmits(["result"]);

const dictStore = useDictInfo();
const billInfoStore = useBillInfo();

const billInfo = ref({} as any);
const editOstInfoStorage = useEditOstInfo();
const shipLandList = ref([] as Array<any>);

onMounted(() => {
  init();
});
billInfoStore.$subscribe(() => {
  init();
});

function init() {
  shipLandList.value = dictStore.getDictByCode("ship_land");
  billInfo.value = billInfoStore.billInfo;
  billInfo.value?.storagePiece + "/" + billInfo.value?.storageTon;
  if (billInfo.value.piece !== 0) {
    const ton = new BigNumber(billInfo.value.ton);
    const piece = new BigNumber(billInfo.value.piece);
    formData.perTon = ton.div(piece).toNumber();
  } else {
    formData.perTon = 0;
  }
}

// 填写件数算吨数
function setPerTon() {
  billInfo.value = billInfoStore.billInfo;
  if (billInfo.value.transportBillId && billInfo.value.piece !== 0) {
    const ton = new BigNumber(billInfo.value.ton);
    const piece = new BigNumber(billInfo.value.piece);
    formData.perTon = ton.div(piece).toNumber();
  } else {
    formData.perTon = 0;
  }
}

function setOriTon() {
  setPerTon();
  if (formData.oriPiece && formData.perTon) {
    formData.oriTon = new BigNumber(formData.oriPiece as string)
      .times(formData.perTon)
      .toString();
  }
}

const formData = reactive({
  shipLand: "",
  operationType: "",
  operationTypeName: "",
  workActivity: [] as string[],
  workActivityName: "",
  assemblyLine: "",
  isRetreat: "N",
  oriStorageInfo: "",
  oriStorageId: "",
  oriStorageAreaId: "",
  oriStorageAreaName: "",
  oriStoragePositionId: "",
  oriStoragePositionName: "",
  oriPackageType: "",
  oriPackageTypeName: "",
  oriSpot: "",
  oriLeftPieceTon: "",
  oriPiece: "",
  oriGoodsPositionId: "",
  oriAreaCode: "",
  oriTon: "",
  perTon: 0,
  toTransportShipId: "",
  toTransportShipName: "",
  toTransportBillId: "",
  toTransportBillNo: "",
  toStorageId: "",
  toStorageAreaId: "",
  toStorageAreaName: "",
  toStoragePositionId: "",
  toStoragePositionName: "",
  toPackageType: "",
  toPackageTypeName: "",
  toPiece: "",
  toTon: "",
  toSpot: "",
  toGoodsPositionId: "",
  toAreaCode: "",
});

watch(
  () => formData,
  newValue => {
    formData.toStorageAreaId = formData.oriStorageAreaId;
    formData.toStorageAreaName = formData.oriStorageAreaName;
    formData.toStoragePositionId = formData.oriStoragePositionId;
    formData.toStoragePositionName = formData.oriStoragePositionName;
    formData.toSpot = formData.oriSpot;
    formData.toGoodsPositionId = formData.oriGoodsPositionId;
    formData.toAreaCode = formData.oriAreaCode;
    formData.toPackageType = formData.oriPackageType;
    formData.toPackageTypeName = formData.oriPackageTypeName;
    formData.toPiece = formData.oriPiece;
    formData.toTon = formData.oriTon;
    emit("result", newValue);
  },
  { immediate: true, deep: true }
);


// 编辑时初始化
watch(
  () => editOstInfoStorage.editOstInfo,
  newValue => {
    formData.shipLand = newValue?.shipLand;
    formData.operationType = newValue?.operationType;
    formData.operationTypeName = newValue?.operationTypeName;
    formData.workActivity = newValue?.workActivity ? newValue?.workActivity.split(",") : [];
    formData.workActivityName = newValue?.workActivityName;
    formData.assemblyLine = newValue?.assemblyLine;
    formData.isRetreat = newValue?.isRetreat;
    if (newValue?.oriStoragePositionId) {
      formData.oriStorageInfo = newValue?.oriStoragePositionName + "-" + newValue?.oriSpot + "-" + newValue?.oriPackageTypeName;
      formData.oriStorageId = newValue?.oriStorageId;
      formData.oriStorageAreaId = newValue?.oriStorageAreaId;
      formData.oriStorageAreaName = newValue?.oriStorageAreaName;
      formData.oriStoragePositionId = newValue?.oriStoragePositionId;
      formData.oriStoragePositionName = newValue?.oriStoragePositionName;
      formData.oriPackageType = newValue?.oriPackageType;
      formData.oriPackageTypeName = newValue?.oriPackageTypeName;
      formData.oriSpot = newValue?.oriSpot;
      formData.oriLeftPieceTon = "";
      formData.oriPiece = newValue?.oriPiece;
      formData.oriTon = newValue?.oriTon;
      formData.oriGoodsPositionId = newValue?.oriGoodsPositionId;
      formData.oriAreaCode = newValue?.oriAreaCode;
    }
    formData.toTransportShipId = newValue?.toTransportShipId;
    formData.toTransportShipName = newValue?.toShipNameZh;
    formData.toTransportBillId = newValue?.toTransportBillId;
    formData.toTransportBillNo = newValue?.toBillNo;
    formData.toStorageAreaId = newValue?.toStorageAreaId;
    formData.toStorageAreaName = newValue?.toStorageAreaName;
    formData.toStoragePositionId = newValue?.toStoragePositionId;
    formData.toStoragePositionName = newValue?.toStoragePositionName;
    formData.toPackageType = newValue?.toPackageType;
    formData.toPackageTypeName = newValue?.toPackageTypeName;
    formData.toPiece = newValue?.toPiece;
    formData.toTon = newValue?.toTon;
    formData.toSpot = newValue?.toSpot;
    formData.toGoodsPositionId = newValue?.toGoodsPositionId;
    formData.toAreaCode = newValue?.toAreaCode;
    getStorageDetail(newValue?.oriStorageId, "watcheditOstInfoStorage");
  },
  { immediate: true }
);

const validator = (val: any) => isNumeric(val);

const showSelectStoragePopup = ref(false);
const isSelectStorageOpen = (value: boolean) => {
  showSelectStoragePopup.value = value;
};
const selectedStorage = (res: StorageData) => {
  if (res.id) {
    formData.oriStorageInfo =
      res.positionName + "-" + res.spot + "-" + res.packageTypeName;
    formData.oriLeftPieceTon = res.piece + "/" + res.ton;
    formData.oriStorageId = res.id;
    formData.oriTon = res.ton;
    formData.oriPiece = String(res.piece);
    formData.oriPackageType = res.packageType;
    formData.oriPackageTypeName = res.packageTypeName;
    formData.oriStorageAreaId = res.areaId;
    formData.oriStorageAreaName = res.areaName;
    formData.oriStoragePositionId = res.positionId;
    formData.oriStoragePositionName = res.positionName;
    formData.oriSpot = res.spot;
    formData.oriGoodsPositionId = res.goodsPositionId;
    formData.oriAreaCode = res.areaCode;

    formData.toPackageType = res.packageType;
    formData.toPackageTypeName = res.packageTypeName;
    formData.toStorageAreaId = res.areaId;
    formData.toStorageAreaName = res.areaName;
    formData.toStoragePositionId = res.positionId;
    formData.toStoragePositionName = res.positionName;
    formData.toSpot = res.spot;
    formData.toTon = res.ton;
    formData.toPiece = String(res.piece);
    formData.toGoodsPositionId = res.goodsPositionId;
    formData.toAreaCode = res.areaCode;
  }
};

function getStorageDetail(id: string, from: string) {
  GetStorageDetail({ id: id }).then((res: any) => {
    formData.oriLeftPieceTon = res.data.piece + "/" + res.data.ton;
  });
}

const showSelectShipPopup = ref(false);

function beforeShowSelectShipPopup() {
  showSelectShipPopup.value = true;
}

const isSelectShipOpen = (value: boolean) => {
  showSelectShipPopup.value = value;
};
const selectedShip = (value: any) => {
  formData.toTransportShipId = value.transportShipId;
  formData.toTransportShipName = value.shipNameZh;
};

const showSelectBillPopup = ref(false);

function beforeShowSelectBillPopup() {
  if (!formData.toTransportShipId) {
    showFailToast("请先选择船");
    return;
  }
  showSelectBillPopup.value = true;
}

const isSelectBillOpen = (value: boolean) => {
  showSelectBillPopup.value = value;
};
const selectedBill = (value: any) => {
  formData.toTransportBillId = value.transportBillId;
  formData.toTransportBillNo = value.billNo;
};

const validate = () => {
};
const onFailed = (value: any) => {
  showFailToast("请检查表单");
};
</script>

<template>
  <form @submit="validate" @failed="onFailed">

    <div
      id="transferInfo"
      class="w-full flex flex-col bg-white py-[10px] px-[15px] rounded-lg mt-3"
    >
      <div class="w h-[40px] flex justify-between">
        <div class="flex h w items-center font-bold">转配信息</div>
      </div>
      <van-cell-group :border="false">
        <van-field
          readonly
          name="position"
          placeholder="请选择货垛"
          is-link
          v-model="formData.oriStorageInfo"
          @click="showSelectStoragePopup = true"
          :rules="[{ required: true, message: '请选择货垛' }]"
        >
          <template #label>货垛<span class="xing">*</span></template>
        </van-field>
        <van-popup
          v-model:show="showSelectStoragePopup"
          position="bottom"
          round
          duration="0"
          class="bg-slate-400 h-[calc(100vh-100px)]"
        >
          <SelectStorage
            :positionId="formData.oriStoragePositionId"
            :storageId="formData.oriStorageId"
            :transportBillId="billInfo.transportBillId"
            @isOpen="isSelectStorageOpen"
            @selectedStorage="selectedStorage"
          ></SelectStorage>
        </van-popup>
        <van-field
          readonly
          disabled
          v-model="formData.oriLeftPieceTon"
          name="leftPieceTon"
          label="货垛剩余"
        />
        <van-field
          readonly
          disabled
          v-model="formData.perTon"
          name="perTon"
          label="舱单单吨"
        />
        <van-field
          name="isRetreat"
          :rules="[{ required: true, message: '请选择退关' }]"
        >
          <template #label>
            退关<span class="xing">*</span>
          </template>
          <template #input>
            <van-radio-group
              shape="dot"
              v-model="formData.isRetreat"
              direction="horizontal"
            >
              <van-radio name="Y" icon-size="18px">是</van-radio>
              <van-radio name="N" icon-size="18px">否</van-radio>
            </van-radio-group>
          </template>
        </van-field>
        <van-field
          name="piece"
          v-model="formData.oriPiece"
          placeholder="请输入件数"
          :rules="[{ validator, message: '请输入件数' }]"
        >
          <template #label>转出件数<span class="xing">*</span></template>
        </van-field>
        <van-field
          name="ton"
          :border="false"
          v-model="formData.oriTon"
          @focus="setOriTon"
          placeholder="请输入吨数"
          :rules="[{ validator, message: '请输入吨数' }]"
        >
          <template #label>转出吨数<span class="xing">*</span></template>
        </van-field>
      </van-cell-group>
    </div>

    <div
      id="tallyTransferForm"
      class="w-full flex flex-col bg-white py-[10px] px-[15px] rounded-lg mt-3"
    >
      <div class="w h-[40px] flex justify-between">
        <div class="flex h w items-center font-bold">转配至</div>
      </div>
      <van-cell-group :border="false">
        <van-field
          :border="true"
          is-link
          readonly
          v-model="formData.toTransportShipName"
          name="shipName"
          placeholder="请选择船名"
          @click="beforeShowSelectShipPopup"
          :rules="[{ required: true, message: '请选择船名' }]"
        >
          <template #label> 船名<span class="xing">*</span></template>
        </van-field>
        <van-popup
          v-model:show="showSelectShipPopup"
          position="bottom"
          round
          duration="0"
          :style="{ height: 'auto' }"
        >
          <SelectShip
            @isOpen="isSelectShipOpen"
            @selectedShip="selectedShip"
          ></SelectShip>
        </van-popup>
        <!-- 选择单号 -->
        <van-field
          :border="false"
          is-link
          readonly
          v-model="formData.toTransportBillNo"
          name="billNo"
          placeholder="请选择单号"
          @click="beforeShowSelectBillPopup"
          :rules="[{ required: true, message: '请选择单号' }]"
        >
          <template #label> 单号<span class="xing">*</span></template>
        </van-field>
        <van-popup
          v-model:show="showSelectBillPopup"
          position="bottom"
          round
          duration="0"
          :style="{ height: 'auto' }"
        >
          <SelectBill
            :shipId="formData.toTransportShipId"
            @isOpen="isSelectBillOpen"
            @selectedBill="selectedBill"
          ></SelectBill>
        </van-popup>
      </van-cell-group>
    </div>

  </form>
  <!-- 作业过程  -->
</template>

<style scoped></style>
